<script setup lang="ts">
import { ref, onMounted, onBeforeUnmount } from 'vue'
import flvjs from 'flv.js'
import type { Player, MediaInfo } from 'flv.js'

const wsUrl = ref<string>('ws://localhost:8443/play?app=live&stream=stream1')
const videoElement = ref<HTMLVideoElement | null>(null)
const flvPlayer = ref<Player | null>(null)
const isPlaying = ref<boolean>(false)
const error = ref<string>('')
const status = ref<string>('')

onMounted(() => {
  if (!flvjs.isSupported()) {
    error.value = 'FLV.js is not supported in current browser'
  }
})

onBeforeUnmount(() => {
  destroyPlayer()
})

const togglePlay = (): void => {
  if (isPlaying.value) {
    stopPlay()
  } else {
    startPlay()
  }
}

const startPlay = (): void => {
  if (!wsUrl.value) {
    error.value = 'Please enter WebSocket URL'
    return
  }

  error.value = ''
  status.value = 'Connecting...'

  try {
    // Destroy old player instance
    destroyPlayer()

    // Create FLV player
    flvPlayer.value = flvjs.createPlayer({
      type: 'flv',
      url: wsUrl.value,
      isLive: true,
      hasAudio: true,
      hasVideo: true,
      cors: true
    }, {
      enableWorker: false,
      enableStashBuffer: false,
      stashInitialSize: 128,
      autoCleanupSourceBuffer: true
    })

    // Attach to video element
    if (videoElement.value) {
      flvPlayer.value.attachMediaElement(videoElement.value)
    }

    // Listen to events
    flvPlayer.value.on(flvjs.Events.ERROR, (errorType: string, errorDetail: string, errorInfo: any) => {
      console.error('FLV Error:', errorType, errorDetail, errorInfo)
      error.value = `Playback error: ${errorType} - ${errorDetail}`
      status.value = ''
      isPlaying.value = false
    })

    flvPlayer.value.on(flvjs.Events.LOADING_COMPLETE, () => {
      status.value = 'Loading complete'
    })

    flvPlayer.value.on(flvjs.Events.MEDIA_INFO, (mediaInfo: MediaInfo) => {
      console.log('Media Info:', mediaInfo)
      status.value = `Video: ${mediaInfo.width}x${mediaInfo.height}`
    })

    // Load and play
    flvPlayer.value.load()
    flvPlayer.value.play().then(() => {
      isPlaying.value = true
      status.value = 'Playing...'
    }).catch((err: Error) => {
      console.error('Play error:', err)
      error.value = 'Playback failed, please check WebSocket URL'
      status.value = ''
    })

  } catch (err) {
    console.error('Player creation error:', err)
    error.value = 'Failed to create player: ' + (err instanceof Error ? err.message : String(err))
    status.value = ''
  }
}

const stopPlay = (): void => {
  destroyPlayer()
  isPlaying.value = false
  status.value = 'Stopped'
}

const destroyPlayer = (): void => {
  if (flvPlayer.value) {
    try {
      flvPlayer.value.pause()
      flvPlayer.value.unload()
      flvPlayer.value.detachMediaElement()
      flvPlayer.value.destroy()
    } catch (err) {
      console.error('Destroy player error:', err)
    }
    flvPlayer.value = null
  }
}
</script>

<template>
  <div class="container">
    <h1>WebSocket FLV Stream Player</h1>
    
    <div class="controls">
      <div class="input-group">
        <label for="wsUrl">WebSocket URL:</label>
        <input
          id="wsUrl"
          v-model="wsUrl"
          type="text"
          placeholder="ws://example.com/live/stream.flv"
          :disabled="isPlaying"
        />
      </div>
      
      <button 
        @click="togglePlay" 
        :class="['play-button', { playing: isPlaying }]"
      >
        {{ isPlaying ? 'Stop' : 'Play' }}
      </button>
    </div>

    <div class="video-container">
      <video 
        ref="videoElement" 
        controls 
        autoplay
      ></video>
      <div v-if="error" class="error-message">{{ error }}</div>
      <div v-if="status" class="status-message">{{ status }}</div>
    </div>
  </div>
</template>

<style scoped>
.container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
}

h1 {
  text-align: center;
  color: #2c3e50;
  margin-bottom: 30px;
  font-size: 2.5rem;
  font-weight: 700;
  letter-spacing: -0.5px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  background-clip: text;
}

.controls {
  display: flex;
  gap: 15px;
  margin-bottom: 20px;
  align-items: flex-end;
}

.input-group {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 8px;
}

label {
  font-weight: 600;
  color: #667eea;
  font-size: 15px;
  letter-spacing: 0.3px;
}

input[type="text"] {
  padding: 12px 15px;
  border: 2px solid #ddd;
  border-radius: 6px;
  font-size: 14px;
  transition: border-color 0.3s;
}

input[type="text"]:focus {
  outline: none;
  border-color: #4CAF50;
}

input[type="text"]:disabled {
  background-color: #f5f5f5;
  cursor: not-allowed;
}

.play-button {
  padding: 12px 40px;
  background-color: #4CAF50;
  color: white;
  border: none;
  border-radius: 6px;
  font-size: 16px;
  font-weight: 600;
  cursor: pointer;
  transition: background-color 0.3s;
  white-space: nowrap;
}

.play-button:hover {
  background-color: #45a049;
}

.play-button.playing {
  background-color: #f44336;
}

.play-button.playing:hover {
  background-color: #da190b;
}

.video-container {
  position: relative;
  background-color: #000;
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
}

video {
  width: 100%;
  height: auto;
  min-height: 400px;
  display: block;
}

.error-message {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  background-color: rgba(244, 67, 54, 0.9);
  color: white;
  padding: 15px 25px;
  border-radius: 6px;
  font-weight: 500;
  max-width: 80%;
  text-align: center;
}

.status-message {
  position: absolute;
  top: 10px;
  right: 10px;
  background-color: rgba(76, 175, 80, 0.9);
  color: white;
  padding: 8px 15px;
  border-radius: 4px;
  font-size: 14px;
  font-weight: 500;
}
</style>
